package com.zzk.protect.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zzk.protect.common.CommonResult;
import com.zzk.protect.config.UserSessionManager;
import com.zzk.protect.pojo.ConstantType;
import com.zzk.protect.pojo.LoginRequest;
import com.zzk.protect.pojo.LoginResponse;
import com.zzk.protect.pojo.User;
import com.zzk.protect.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private UserSessionManager userSessionManager;
    // 获取用户列表
    @GetMapping("/list")
    public CommonResult<List<User>> list() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> list = userService.list(queryWrapper);
        return CommonResult.success(list);
    }

    // 添加用户
    @PostMapping("/add")
    public CommonResult add(@RequestBody User user) {
        // 检查用户名是否已存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();


        return CommonResult.success(userService.save(user));
    }

    // 删除用户（逻辑删除）
    @DeleteMapping("/delete/{id}")
    public CommonResult delete(@PathVariable Integer id) {
        User user = new User();
        user.setId(id);
        user.setIsDeleted(0); // 0表示不存在/禁用状态
        return CommonResult.success(userService.updateById(user));
    }

    // 切换用户状态
    @PostMapping("/status")
    public CommonResult status(@RequestBody User user) {
        User entity = new User();
        entity.setId(user.getId());
        // 切换状态：1<->0
        entity.setIsDeleted(user.getIsDeleted() == 1 ? 1 : 0);
        return CommonResult.success(userService.updateById(entity));
    }

    // 更新用户信息
    @PostMapping("/update")
    public CommonResult update(@RequestBody User user) {
        // 检查用户名是否已存在（排除自己）
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("is_deleted", 1); // 检查存在的用户
        queryWrapper.ne("id", user.getId());
        if (userService.count(queryWrapper) > 0) {
            return CommonResult.failed("用户名已存在");
        }
        return CommonResult.success(userService.updateById(user));
    }
    @PostMapping("/login")
    public CommonResult<LoginResponse> login(@RequestBody LoginRequest loginRequest, HttpServletResponse response) {
        // 参数校验
        if (StringUtils.isEmpty(loginRequest.getUsername())) {
            return CommonResult.failed("用户名不能为空");
        }
        if (StringUtils.isEmpty(loginRequest.getPassword())) {
            return CommonResult.failed("密码不能为空");
        }

        // 查询用户
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", loginRequest.getUsername())
                .eq("password", loginRequest.getPassword());
        User user = userService.getOne(qw);

        if (user == null) {
            return CommonResult.failed("用户名或密码错误");
        }

        // 创建会话并返回sessionId
        String sessionId = userSessionManager.addUserSession(user);

        // 创建响应对象
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setSessionId(sessionId);
        loginResponse.setUser(user);
        return CommonResult.success(loginResponse);
    }
    @GetMapping("/current")
    public CommonResult<User> getCurrentUser(@RequestParam(required = false) String sessionId,
                                             HttpServletRequest request) {
        // 从参数或cookie中获取sessionId
        String actualSessionId = sessionId;
        if (actualSessionId == null) {
            return CommonResult.failed("未登录");
        }

        User user = userSessionManager.getUserBySessionId(actualSessionId);
        if (user == null) {
            return CommonResult.failed("会话已过期，请重新登录");
        }

        return CommonResult.success(user);
    }

    @PostMapping("/logout")
    public CommonResult<String> logout(@RequestParam String sessionId) {
        userSessionManager.removeUserSession(sessionId);
        return CommonResult.success("登出成功");
    }
    @GetMapping("/getByDeptId")
    public CommonResult<List<User>> getByDeptId(@RequestParam Integer deptId){
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("department_id",deptId).eq("user_type",3);
        return CommonResult.success(userService.list(qw));
}

}
    // 根据ID或姓名查询用户
//    @GetMapping("/search")
//    public CommonResult search(@RequestParam(required = false) String keyword) {
//        try {
//            List<User> result = userService.searchByIdOrName(keyword);
//            return CommonResult.success(result);
//        } catch (Exception e) {
//            return CommonResult.failed("查询失败: " + e.getMessage());
//        }
//    }

